import React, {Component} from "react";
import PropTypes from "prop-types";
import './index.css'

export class UserItem extends Component {
    
    state = {
        mouse: false
    }
    static propTypes = {
        item:PropTypes.object.isRequired,
        deleteTodo:PropTypes.func.isRequired,
        checkDone:PropTypes.func.isRequired
    }
    render() {
        let {item} = this.props;
        const {mouse} = this.state;
        return (
            <li
                style={{backgroundColor: mouse ? "#ddd" : "white"}}
                onMouseEnter={this.handleMouse(true)}
                onMouseLeave={this.handleMouse(false)}
            >
                <label>
                    <input type="checkbox" onChange={this.handleChange(item.id)} checked={item.done}/>
                    <span>{item.title}</span>
                </label>
                <button
                    className="btn btn-danger"
                    style={{display: mouse ? "block" : "none"}}
                    onClick={this.handleDelete(item.id)}
                >删除
                </button>
            </li>
        )
    }
    
    // true 表示移入 false 表示移出
    handleMouse = (flag) => {
        return (event) => {
            this.setState({mouse: flag})
        }
    }
    
    handleDelete(id) {
        return () => {
            if(window.confirm("确认删除吗?")){
                this.props.deleteTodo(id);
            }
        };
    }
    
    handleChange = (id) => {
        return (e) => {
            this.props.checkDone(id, e.target.checked)
        };
    }
}